<template>
	<view class="shangban-container">
		<!-- 下拉刷新提示 -->
		<view class="refresh-tip" v-if="!loading && roomList.length > 0">
			<text class="tip-text">下拉刷新数据</text>
		
		</view>
		
					<!-- 管理层专属用户搜索栏 -->
		<view v-if="isGuanliceng" class="guanliceng-user-search">
			<view class="search-item">
				<text class="search-label">工号</text>
				<input class="search-input" v-model="userSearchEmployeeId" placeholder="请输入工号" />
			</view>
				<!-- 用户选择弹窗/下拉 -->
				<view v-if="userSearchShow" class="user-search-list">
				<view class="user-item" v-for="user in userSearchList" :key="user.userId" @click="handleSelectUser(user)">
					<text>{{ user.userName }}（{{ user.employeeId }}）</text>
				</view>
			</view>
			<view class="search-buttons">
				<button class="search-btn" :loading="userSearchLoading" @click="handleUserSearch">查找用户</button>
				<!-- <button class="search-btn" :loading="userSearchLoading" @click="handleRoomSearch">查找房间</button> -->
			</view>
			
			<view class="search-item">
				<text class="search-label">房间名称</text>
				<input class="search-input" v-model="userSearchRoomName" placeholder="请输入房间名称" />
			</view>
			
			<view class="search-item">
				<text class="search-label">日期</text>
				<picker 
					mode="date" 
					:value="userSearchDate" 
					@change="handleUserSearchDateChange"
					class="date-picker"
				>
					<view class="picker-text">{{ userSearchDate || '请选择日期' }}</view>
				</picker>
			</view>
		
			<view class="search-buttons">
				<!-- <button class="search-btn" :loading="userSearchLoading" @click="handleUserSearch">查找用户</button> -->
				<button class="search-btn" :class="{'search-btn-disabled': !userSearchDate || !userSearchRoomName}" :loading="userSearchLoading" @click="handleRoomSearch" :disabled="!userSearchDate || !userSearchRoomName">查找房间</button>
			</view>
			
		
		</view>
		<!-- 业务员状态展示 -->
		<!-- <view class="status-section" v-if="isBusiness">
			<view class="status-title">当前状态：</view>
			<view class="status-buttons">
				<view 
					class="status-btn" 
					:class="{ active: currentStatus === 'normal', disabled: currentStatus === 'applying' }"
					@click="currentStatus !== 'applying' && changeStatus('normal')"
				>正常</view>
				<view 
					class="status-btn" 
					:class="{ active: currentStatus === 'chuantai', disabled: currentStatus === 'applying' }"
					@click="currentStatus !== 'applying' && changeStatus('chuantai')"
				>串台</view>
				<view 
					class="status-btn applying" 
					:class="{ active: currentStatus === 'applying' }"
					v-if="currentStatus === 'applying'"
				>申请串台中</view>
			</view>
		</view> -->

		<!-- 业务经理查看申请列表 -->
		<view class="apply-list" v-if="isManager">
			<view class="section-title">串台申请列表</view>
			<view class="apply-item" v-for="(item, index) in applyList" :key="index">
				<view class="apply-info">
					<view class="info-row">
						<text class="label">申请人：</text>
						<text class="value">{{ item.userName }}</text>
					</view>
					<view class="info-row">
						<text class="label">工号：</text>
						<text class="value">{{ item.employeeId }}</text>
					</view>
					<view class="info-row">
						<text class="label">房间名：</text>
						<text class="value">{{ item.bb }}</text>
					</view>
				</view>
				<view class="apply-action">
					<button class="approve-btn" @click="handleApprove(item)">通过</button>
					<button class="reject-btn" @click="handleReject(item)">拒绝</button>
				</view>
			</view>
			<view v-if="applyList.length === 0" class="no-data">暂无申请</view>
		</view>

		<!-- 申请移除列表 -->
		<view class="apply-list" v-if="isManager">
			<view class="section-title">申请移除列表</view>
			<view class="apply-item" v-for="(item, index) in removeApplyList" :key="index">
				<view class="apply-info">
					<view class="info-row">
						<text class="label">申请人：</text>
						<text class="value">{{ item.userName }}</text>
					</view>
					<view class="info-row">
						<text class="label">工号：</text>
						<text class="value">{{ item.employeeId }}</text>
					</view>
					<view class="info-row">
						<text class="label">房间ID：</text>
						<text class="value">{{ item.gg || '未知' }}</text>
					</view>
				</view>
				<view class="apply-action">
					<button class="approve-btn" @click="handleRemoveApprove(item)">通过</button>
					<button class="reject-btn" @click="handleRemoveReject(item)">拒绝</button>
				</view>
			</view>
			<view v-if="removeApplyList.length === 0" class="no-data">暂无申请</view>
		</view>

		<!-- 搜索区域 -->
		<!-- <view class="search-section">
			<view class="search-item">
				<text class="search-label">房间名称</text>
				<input 
					class="search-input" 
					type="text" 
					v-model="searchForm.roomName" 
					placeholder="请输入房间名称"
				/>
			</view>
			<view class="search-item">
				<text class="search-label">日期</text>
				<picker 
					mode="date" 
					:value="searchForm.recordTime" 
					@change="handleDateChange"
					class="date-picker"
				>
					<view class="picker-text">{{ searchForm.recordTime || '请选择日期' }}</view>
				</picker>
			</view>
			<view class="search-buttons">
				<button class="search-btn" @click="handleSearch">搜索</button>
				<button class="reset-btn" @click="handleReset">重置</button>
			</view>
		</view> -->

	

		<view class="data-list">
			<view v-if="loading" class="loading">加载中...</view>
			<view v-else>
			<view class="data-item" v-for="(item, index) in roomList" :key="index">
				<view class="item-header">
					<view class="date">{{ formatDate(item.recordTime) }}</view>
					<!-- <view class="booker">订房人: {{ item.bookerName || '暂无' }}</view> -->
				</view>
				<view class="item-body">
					<view class="info-row">
						<text class="label">房间名称:</text>
							<text class="value">{{ item.cc || item.roomId }}</text>
					</view>
					<view class="info-row">
						<text class="label">开始时间:</text>
						<text class="value">{{ formatDate(item.createdAt) }}</text>
					</view>
					<!-- <view class="info-row">
						<text class="label">状态:</text>
						<text class="value">{{ getStatusText(item.status) }}</text>
					</view>
					<view class="info-row">
						<text class="label">用途:</text>
						<text class="value">{{ item.purpose || '暂无' }}</text>
					</view> -->
					<!-- 新增：订房人信息 -->
					<view class="info-row">
						<text class="label">订房人:</text>
						<text class="value">{{ item.bookerName || item.bookerId || '暂无' }}</text>
					</view>
					<!-- 新增：服务员信息 -->
					<view class="info-row">
						<text class="label">服务员:</text>
						<text class="value">{{ item.serviceStaffName || item.serviceStaffId || '暂无' }}</text>
					</view>
					<!-- 新增：DJ信息 -->
					<view class="info-row">
						<text class="label">DJ:</text>
						<text class="value">{{ item.djName || item.djId || '暂无' }}</text>
					</view>
					<!-- 新增：轮房人信息 -->
					<view class="info-row">
						<text class="label">轮房人:</text>
						<text class="value">{{ item.ee || item.ff || '暂无' }}</text>
					</view>
					<!-- 新增：业务员列表 -->
					<view class="info-row" >
						<text class="label">业务员:</text>
						<view class="value">
							<view class="salesperson-list">
								<view class="salesperson-item" v-for="(salesperson, index) in item.salespersonList" :key="index">
									<view class="salesperson-info">
										<text class="salesperson-name">{{ salesperson.name }}</text>
										<text class="salesperson-id">-{{ salesperson.employeeId }}-</text>
									</view>
									<text class="salesperson-level">{{ salesperson.level }}</text>
								</view>
							</view>
						</view>
					</view>
					
					<!-- <view class="info-row">
						<text class="label">结束时间:</text>
						<text class="value">{{ formatDate(item.endTime) }}</text>
					</view> -->
				<!-- 	<view class="info-row">
						<text class="label">总金额:</text>
						<text class="value">{{ item.totalAmount || '0.00' }}</text>
					</view>
					<view class="info-row">
						<text class="label">折扣:</text>
						<text class="value">{{ item.discount || '0' }}</text>
					</view> -->
					<view class="info-row">
						<text class="label">服务人员结算:</text>
						<text class="value">{{ item.serviceStaffPayment || '暂无' }}</text>
					</view>
					<view class="info-row">
						<text class="label">DJ结算:</text>
						<text class="value">{{ item.djPayment || '暂无' }}</text>
					</view>
					<view class="info-row">
						<text class="label">业务员结算:</text>
						<text class="value">{{ item.salespersonPayment || '暂无' }}</text>
					</view>
					<view class="info-row" v-if="item.remark">
						<text class="label">房间公告:</text>
						<text class="value">{{ item.remark }}</text>
					</view>
				</view>
			</view>
				<view v-if="!loading && roomList.length === 0" class="no-data">暂无数据</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { searchRoomRecordUser } from '@/api/system/room'
	import { searchRoomRecordByCcAndTime } from '@/api/system/roomrecord'
	import { getUser ,updateUser,listUser,eelistUser,fflistUser} from '@/api/system/user'
	import { removeSalespersonFromRoomGroup } from '@/api/system/room'
	import { updateAttendance, addAttendance, listAttendance } from '@/api/system/attendance'
	
	export default {
		data() {
			return {
				roomList: [],
				loading: true,
				searchForm: {
					roomName: '',
					recordTime: ''
				},
				originalList: [], // 存储原始数据
				isBusiness: false, // 是否是业务员
				isManager: false, // 是否是业务经理
				isGuanliceng: false, // 是否是管理层
				currentStatus: 'normal', // 当前状态：normal-正常，chuantai-串台
				userStatus: null, // 用户状态
				applyList: [], // 申请列表
				removeApplyList: [], // 新增的移除申请列表
				// 管理层用户搜索相关
				userSearchEmployeeId: '',
				userSearchRoomName: '', // 新增：房间名称搜索
				userSearchDate: '', // 新增：日期搜索
				userSearchList: [],
				userSearchLoading: false,
				userSearchShow: false,
				// 下拉刷新相关
				isRefreshing: false,
				// 用户信息缓存
				userInfoCache: {}
			}
		},
		onLoad() {
			// 检查角色
			const roles = uni.getStorageSync('roles') || []
			this.isBusiness = roles.includes('yewuyuan')
			this.isManager = roles.includes('duchayuan')
			this.isGuanliceng = roles.includes('guanliceng')
			
			if (this.isBusiness) {
				this.getUserStatus()
			}
			if (this.isManager) {
				this.getApplyList()
				this.getRemoveApplyList()
			}
			this.getRoomList()
		},
		
		// 下拉刷新
		onPullDownRefresh() {
			this.handleRefresh()
		},
		methods: {
			// 下拉刷新处理
			async handleRefresh() {
				if (this.isRefreshing) return
				
				this.isRefreshing = true
				
				// 只有在非下拉刷新状态下才显示loading
				if (!uni.getSystemInfoSync().platform.includes('devtools')) {
					uni.showLoading({
						title: '刷新中...'
					})
				}
				
				try {
					// 并行刷新所有数据
					const promises = []
					
					// 刷新房间列表
					promises.push(this.getRoomList())
					
					// 如果是业务员，刷新用户状态
					if (this.isBusiness) {
						promises.push(this.getUserStatus())
					}
					
					// 如果是业务经理，刷新申请列表
					if (this.isManager) {
						promises.push(this.getApplyList())
						promises.push(this.getRemoveApplyList())
					}
					
					// 等待所有请求完成，使用 Promise.allSettled 来处理部分失败的情况
					const results = await Promise.allSettled(promises)
					
					// 检查是否有失败的请求
					const failedResults = results.filter(result => result.status === 'rejected')
					
					if (failedResults.length === 0) {
						uni.showToast({
							title: '刷新成功',
							icon: 'success',
							duration: 1500
						})
					} else {
						console.warn('部分数据刷新失败:', failedResults)
						uni.showToast({
							title: '部分数据刷新失败',
							icon: 'none',
							duration: 1500
						})
					}
				} catch (error) {
					console.error('刷新数据失败:', error)
					uni.showToast({
						title: '刷新失败',
						icon: 'none',
						duration: 1500
					})
				} finally {
					this.isRefreshing = false
					uni.hideLoading()
					uni.stopPullDownRefresh()
				}
			},
			
			// 获取用户状态
			async getUserStatus() {
				try {
					const userInfo = uni.getStorageSync('userInfo')
					if (userInfo && userInfo.user) {
						const userId = userInfo.user.userId
						const res = await getUser(userId)
						if (res.code === 200 && res.data) {
							const userData = res.data
							// 根据ee字段的值设置状态
							if (userData.ee === '申请串台') {
								this.userStatus = 'applying'
								this.currentStatus = 'applying'
							} else if (userData.ee === '正常') {
								this.userStatus = 'normal'
								this.currentStatus = 'normal'
							} else {
								this.userStatus = 'chuantai'
								this.currentStatus = 'chuantai'
							}
						} else {
							if (!this.isRefreshing) {
								console.error('获取用户状态失败: 响应数据异常')
							}
							throw new Error('获取用户状态失败: 响应数据异常')
						}
					} else {
						if (!this.isRefreshing) {
							console.error('获取用户状态失败: 未获取到用户信息')
						}
						throw new Error('获取用户状态失败: 未获取到用户信息')
					}
				} catch (error) {
					console.error('获取用户状态失败:', error)
					if (!this.isRefreshing) {
						// 在非刷新状态下，可以选择是否显示错误提示
						// 这里选择不显示，因为用户状态获取失败不影响主要功能
					}
					throw error
				}
			},
			// 切换状态
			async changeStatus(status) {
				try {
					const userInfo = uni.getStorageSync('userInfo')
					if (userInfo && userInfo.user) {
						const userId = userInfo.user.userId
						
						// 获取完整的用户信息
						const userRes = await getUser(userId)
						if (userRes.code !== 200 || !userRes.data) {
							uni.showToast({
								title: '获取用户信息失败',
								icon: 'none'
							})
							return
						}
						
						const userData = userRes.data
						
						// 确保roleIds是数组
						const roleIds = userRes.roleIds || []
						
						// 如果是切换到串台状态，显示确认弹窗
						if (status === 'chuantai') {
							uni.showModal({
								title: '申请串台',
								content: '是否确认申请串台？',
								success: async (modalRes) => {
									if (modalRes.confirm) {
										// 调用更新接口，传递完整的用户信息
										const updateRes = await updateUser({
											...userData,
											roleIds: roleIds,
											ee: '申请串台'
										})
										
										if (updateRes.code === 200) {
											this.currentStatus = 'applying' // 申请中状态
											this.userStatus = 'applying'
											uni.showToast({
												title: '申请已提交',
												icon: 'success'
											})
										} else {
											uni.showToast({
												title: updateRes.msg || '申请失败',
												icon: 'none'
											})
										}
									}
								}
							})
						} else {
							// 切换回正常状态
							const updateRes = await updateUser({
								...userData,
								roleIds: roleIds,
								ee: '正常'
							})
							
							if (updateRes.code === 200) {
								this.currentStatus = 'normal'
								this.userStatus = 'normal'
								uni.showToast({
									title: '已切换为正常状态',
									icon: 'success'
								})
							} else {
								uni.showToast({
									title: updateRes.msg || '状态更新失败',
									icon: 'none'
								})
							}
						}
					}
				} catch (error) {
					console.error('更新状态失败:', error)
					uni.showToast({
						title: '状态更新失败',
						icon: 'none'
					})
				}
			},
			// 获取房间列表
			async getRoomList() {
				// 如果不是刷新状态，显示loading
				if (!this.isRefreshing) {
				this.loading = true;
				}
				
				try {
					const userInfo = uni.getStorageSync('userInfo')
					if (userInfo && userInfo.user) {
						const userId = userInfo.user.userId
						const res = await searchRoomRecordUser({ userId: userId })
						if (res.code === 200) {
							this.originalList = res.data
							// 为每个房间项添加业务员列表信息
							await this.addSalespersonListToRooms(this.originalList)
							this.filterList()
						} else {
							if (!this.isRefreshing) {
							this.$modal.msgError(res.msg || '获取数据失败')
							}
							throw new Error(res.msg || '获取数据失败')
						}
					} else {
						if (!this.isRefreshing) {
						this.$modal.msgError('未获取到用户信息')
						}
						throw new Error('未获取到用户信息')
					}
				} catch (error) {
					console.error('获取房间列表失败:', error)
					if (!this.isRefreshing) {
					this.$modal.msgError('获取数据失败')
					}
					throw error
				} finally {
					if (!this.isRefreshing) {
					this.loading = false;
					}
				}
			},
			// 处理日期选择
			handleDateChange(e) {
				this.searchForm.recordTime = e.detail.value;
			},
			// 处理搜索
			handleSearch() {
				this.filterList()
			},
			// 处理重置
			handleReset() {
				this.searchForm = {
					roomName: '',
					recordTime: ''
				}
				this.roomList = [...this.originalList]
			},
			// 过滤列表
			filterList() {
				let filteredList = [...this.originalList];
				
				// 按房间名称筛选
				if (this.searchForm.roomName) {
					filteredList = filteredList.filter(item => {
						if (!item.cc) return false;
						return item.cc.includes(this.searchForm.roomName);
					});
				}
				
				// 按日期筛选
				if (this.searchForm.recordTime) {
					filteredList = filteredList.filter(item => {
						if (!item.recordTime) return false;
						// 取前10位（yyyy-MM-dd）
						const itemDate = item.recordTime.length >= 10 ? item.recordTime.slice(0, 10) : this.formatDate(item.recordTime);
						return itemDate === this.searchForm.recordTime;
					});
				}
				
				this.roomList = filteredList;
			},
			getStatusText(status) {
				const statusMap = {
					'booked': '已预订',
					'available': '可用',
					'checkout': '已退房',
					'union': '已合并'
				}
				return statusMap[status] || status
			},
			formatDate(dateStr) {
				if (!dateStr) return '暂无'
				const date = new Date(dateStr)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
			},
			// 获取申请列表
			async getApplyList() {
				try {
					const res = await eelistUser({
						ee: '申请串台'
					})
					if (res.code === 200) {
						this.applyList = res.rows || []
					} else {
						if (!this.isRefreshing) {
						uni.showToast({
							title: res.msg || '获取申请列表失败',
							icon: 'none'
						})
						}
						throw new Error(res.msg || '获取申请列表失败')
					}
				} catch (error) {
					console.error('获取申请列表失败:', error)
					if (!this.isRefreshing) {
					uni.showToast({
						title: '获取申请列表失败',
						icon: 'none'
					})
					}
					throw error
				}
			},
			// 处理申请
			async handleApprove(user) {
				try {
					uni.showModal({
						title: '确认通过',
						content: `是否通过 ${user.userName} 的串台申请？`,
						success: async (modalRes) => {
							if (modalRes.confirm) {
								// 获取完整的用户信息
								const userRes = await getUser(user.userId)
								if (userRes.code !== 200 || !userRes.data) {
									uni.showToast({
										title: '获取用户信息失败',
										icon: 'none'
									})
									return
								}
								
								const userData = userRes.data
								
								// 确保roleIds是数组
								const roleIds = userRes.roleIds || []
								
								// 更新用户状态为串台
								const updateRes = await updateUser({
									...userData,
									roleIds: roleIds,
									ee: '串台'
								})
								
								if (updateRes.code === 200) {
									uni.showToast({
										title: '已通过申请',
										icon: 'success'
									})
									// 刷新申请列表
									this.getApplyList()
									// 同时刷新移除申请列表，确保数据同步
									this.getRemoveApplyList()
								} else {
									uni.showToast({
										title: updateRes.msg || '操作失败',
										icon: 'none'
									})
								}
							}
						}
					})
				} catch (error) {
					console.error('处理申请失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			},
			// 处理拒绝串台申请
			async handleReject(user) {
				try {
					uni.showModal({
						title: '确认拒绝',
						content: `是否拒绝 ${user.userName} 的串台申请？`,
						success: async (modalRes) => {
							if (modalRes.confirm) {
								// 获取完整的用户信息
								const userRes = await getUser(user.userId)
								if (userRes.code !== 200 || !userRes.data) {
									uni.showToast({
										title: '获取用户信息失败',
										icon: 'none'
									})
									return
								}
								
								const userData = userRes.data
								
								// 确保roleIds是数组
								const roleIds = userRes.roleIds || []
								
								// 更新用户状态为拒绝串台
								const updateRes = await updateUser({
									...userData,
									roleIds: roleIds,
									ee: '拒绝串台'
								})
								
								if (updateRes.code === 200) {
									uni.showToast({
										title: '已拒绝申请',
										icon: 'success'
									})
									// 刷新申请列表
									this.getApplyList()
									// 同时刷新移除申请列表，确保数据同步
									this.getRemoveApplyList()
								} else {
									uni.showToast({
										title: updateRes.msg || '操作失败',
										icon: 'none'
									})
								}
							}
						}
					})
				} catch (error) {
					console.error('处理拒绝申请失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			},
			// 新增的移除申请处理方法
			async handleRemoveApprove(item) {
				try {
					uni.showModal({
						title: '确认通过',
						content: `是否通过 ${item.userName} 的移除申请？`,
						success: async (modalRes) => {
							if (modalRes.confirm) {
								try {
									// 获取完整的用户信息
									const userRes = await getUser(item.userId)
									if (userRes.code !== 200 || !userRes.data) {
										uni.showToast({
											title: '获取用户信息失败',
											icon: 'none'
										})
										return
									}
									
									const userData = userRes.data
									const roomId = item.gg // 从gg字段获取房间ID
									
									if (!roomId) {
										uni.showToast({
											title: '未找到相关房间信息',
											icon: 'none'
										})
										return
									}
									
									console.log('调用移除接口，参数:', { roomId, salespersonUserId: item.userId })
									
									// 先调用移除接口把用户从房间中移出
									const removeRes = await removeSalespersonFromRoomGroup({ 
										roomId: roomId, 
										salespersonUserId: item.userId 
									})
									
									console.log('移除接口返回:', removeRes)
									
									if (removeRes.code !== 200) {
										uni.showToast({
											title: removeRes.msg || '移除用户失败',
											icon: 'none'
										})
										return
									}
									
									// 确保roleIds是数组
									const roleIds = userRes.roleIds || []
									
									// 移除成功后，更新用户状态，清除ff和gg字段
									const updateRes = await updateUser({
										...userData,
										roleIds: roleIds,
										ff: '', // 清除申请移除状态
										gg: '' // 清除房间ID
									})
									
									if (updateRes.code === 200) {
										uni.showToast({
											title: '已通过移除申请',
											icon: 'success'
										})
										// 刷新移除申请列表
										this.getRemoveApplyList()
										// 同时刷新串台申请列表，确保数据同步
										this.getApplyList()
										
										//   在这里更新业务员当天的考勤信息
										try {
											const today = new Date();
											const yyyy = today.getFullYear();
											const mm = String(today.getMonth() + 1).padStart(2, '0');
											const dd = String(today.getDate()).padStart(2, '0');
											const punchDate = `${yyyy}-${mm}-${dd}`;
											// 查询当天考勤
											const attRes = await listAttendance({ userId: item.userId, punchDate });
											if (attRes.code === 200 && attRes.rows && attRes.rows.length > 0) {
												// 已有考勤，更新
												const attendance = attRes.rows[0];
												await updateAttendance({
													id: attendance.id,
													userId: item.userId,
													userName: item.userName,
													punchDate,
													aa: '业务员打卡'
												});
											} else {
												// 没有考勤，不新增，提示
												console.log('业务员未分配号码，无法更新考勤');
											}
										} catch (e) {
											console.error('更新业务员考勤信息失败', e);
										}
										
										
									} else {
										uni.showToast({
											title: updateRes.msg || '更新用户状态失败',
											icon: 'none'
										})
									}
								} catch (error) {
									console.error('处理移除申请失败:', error)
									uni.showToast({
										title: '操作失败',
										icon: 'none'
									})
								}
							}
						}
					})
				} catch (error) {
					console.error('处理移除申请失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			},
			// 处理拒绝移除申请
			async handleRemoveReject(item) {
				try {
					uni.showModal({
						title: '确认拒绝',
						content: `是否拒绝 ${item.userName} 的移除申请？`,
						success: async (modalRes) => {
							if (modalRes.confirm) {
								try {
									// 获取完整的用户信息
									const userRes = await getUser(item.userId)
									if (userRes.code !== 200 || !userRes.data) {
										uni.showToast({
											title: '获取用户信息失败',
											icon: 'none'
										})
										return
									}
									
									const userData = userRes.data
									
									// 确保roleIds是数组
									const roleIds = userRes.roleIds || []
									
									// 拒绝移除申请，更新用户状态，清除ff和gg字段
									const updateRes = await updateUser({
										...userData,
										roleIds: roleIds,
										ff: '拒绝移除', // 设置为拒绝移除状态
										gg: '' // 清除房间ID
									})
									
									if (updateRes.code === 200) {
										uni.showToast({
											title: '已拒绝移除申请',
											icon: 'success'
										})
										// 刷新移除申请列表
										this.getRemoveApplyList()

										// 同时刷新串台申请列表，确保数据同步
										this.getApplyList()

	

									} else {
										uni.showToast({
											title: updateRes.msg || '更新用户状态失败',
											icon: 'none'
										})
									}
								} catch (error) {
									console.error('处理拒绝移除申请失败:', error)
									uni.showToast({
										title: '操作失败',
										icon: 'none'
									})
								}
							}
						}
					})
				} catch (error) {
					console.error('处理拒绝移除申请失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			},
			// 获取移除申请列表
			async getRemoveApplyList() {
				try {
					const res = await fflistUser({
						ff: '申请移除'
					})
					if (res.code === 200) {
						this.removeApplyList = res.rows || []
					} else {
						if (!this.isRefreshing) {
						uni.showToast({
							title: res.msg || '获取移除申请列表失败',
							icon: 'none'
						})
						}
						throw new Error(res.msg || '获取移除申请列表失败')
					}
				} catch (error) {
					console.error('获取移除申请列表失败:', error)
					if (!this.isRefreshing) {
					uni.showToast({
						title: '获取移除申请列表失败',
						icon: 'none'
					})
					}
					throw error
				}
			},
			// 处理管理层搜索日期选择
			handleUserSearchDateChange(e) {
				this.userSearchDate = e.detail.value;
			},
			
			// 管理层用户搜索
			async handleUserSearch() {
				if (!this.userSearchEmployeeId) {
					uni.showToast({ title: '请输入工号', icon: 'none' })
					return
				}
				this.userSearchLoading = true
				try {
					const res = await listUser({ employeeId: this.userSearchEmployeeId })
					if (res.code === 200 && res.rows && res.rows.length > 0) {
						this.userSearchList = res.rows
						this.userSearchShow = true
					} else {
						this.userSearchList = []
						this.userSearchShow = false
						uni.showToast({ title: '未找到相关用户', icon: 'none' })
					}
				} catch (e) {
					uni.showToast({ title: '查询失败', icon: 'none' })
				} finally {
					this.userSearchLoading = false
				}
			},
			// 选择用户后查房间
			async handleSelectUser(user) {
				this.userSearchShow = false
				this.userSearchEmployeeId = user.employeeId
				this.loading = true
				try {
					const res = await searchRoomRecordUser({ userId: user.userId })
					if (res.code === 200) {
						this.originalList = res.data
						// 为每个房间项添加业务员列表信息
						await this.addSalespersonListToRooms(this.originalList)
						this.filterList()
					} else {
						this.$modal.msgError(res.msg || '获取数据失败')
					}
				} catch (e) {
					this.$modal.msgError('获取数据失败')
				} finally {
					this.loading = false
				}
			},

			
			// 管理层房间搜索
			async handleRoomSearch() {
				if (!this.userSearchDate) {
					uni.showToast({ title: '请先选择日期', icon: 'none' })
					return
				}
				if (!this.userSearchRoomName) {
					uni.showToast({ title: '请输入房间名称', icon: 'none' })
					return
				}
				
				this.userSearchLoading = true
				this.loading = true
				try {
					// 构建搜索参数
					const searchParams = {}
					// 房间名称是必填的
					searchParams.cc = this.userSearchRoomName // 房间名称对应cc字段
					// 日期是必填的
					searchParams.recordTime = this.userSearchDate // 日期搜索
					
					// 调用房间记录搜索API
					const res = await searchRoomRecordByCcAndTime(searchParams)
					if (res.code === 200) {
						this.originalList = res.data || []
						// 为每个房间项添加业务员列表信息
						await this.addSalespersonListToRooms(this.originalList)
						this.filterList()
						
						if (this.originalList.length === 0) {
							uni.showToast({ title: '未找到相关房间记录', icon: 'none' })
						} else {
							uni.showToast({ 
								title: `找到 ${this.originalList.length} 条记录`, 
								icon: 'success' 
							})
						}
					} else {
						this.$modal.msgError(res.msg || '搜索房间记录失败')
					}
				} catch (e) {
					console.error('房间搜索失败:', e)
					this.$modal.msgError('搜索房间记录失败')
				} finally {
					this.userSearchLoading = false
					this.loading = false
				}
			},
			// 获取用户信息（带缓存）
			async getUserInfo(userId) {
				if (!userId) return null;
				
				// 如果已经有缓存，直接返回
				if (this.userInfoCache && this.userInfoCache[userId]) {
					return this.userInfoCache[userId];
				}
				
				try {
					const res = await getUser(userId);
					if (res.code === 200 && res.data) {
						const userData = res.data;
						const userInfo = {
							name: userData.userName || userData.nickName || `用户${userId}`,
							employeeId: userData.employeeId || userId,
							level: userData.level || '无'
						};
						
						// 缓存用户信息
						if (!this.userInfoCache) {
							this.userInfoCache = {};
						}
						this.userInfoCache[userId] = userInfo;
						
						return userInfo;
					}
				} catch (error) {
					console.error('获取用户信息失败:', error);
				}
				
				return null;
			},
			
			// 获取业务员列表（用于模板调用）
			async getSalespersonList(groupName) {
				if (!groupName) return [];
				
				const userIds = groupName.split(',').filter(id => id.trim());
				const salespersonList = [];
				
				console.log('解析业务员列表，groupName:', groupName, 'userIds:', userIds);
				
				// 并行获取所有用户信息
				const userPromises = userIds.map(async (userId) => {
					const userInfo = await this.getUserInfo(userId.trim());
					if (userInfo) {
						console.log('获取到用户信息:', userInfo);
						return userInfo;
					} else {
						console.log('用户信息获取失败，使用兜底显示');
						return {
							name: `用户${userId.trim()}`,
							employeeId: userId.trim(),
							level: '无'
						};
					}
				});
				
				// 等待所有用户信息获取完成
				const results = await Promise.allSettled(userPromises);
				results.forEach(result => {
					if (result.status === 'fulfilled') {
						salespersonList.push(result.value);
					} else {
						console.error('获取用户信息失败:', result.reason);
					}
				});
				
				console.log('最终业务员列表:', salespersonList);
				return salespersonList;
			},
			// 为房间列表添加业务员列表信息
			async addSalespersonListToRooms(rooms) {
				console.log('开始处理房间列表，房间数量:', rooms.length);
				for (const room of rooms) {
					console.log('处理房间:', room.id, 'groupName:', room.groupName, 'businessUsers:', room.businessUsers);
					
					// 如果后端已经提供了业务员信息
					if (room.businessUsers && Array.isArray(room.businessUsers)) {
						console.log('使用后端提供的业务员信息:', room.businessUsers);
						room.salespersonList = room.businessUsers.map(user => ({
							name: user.userName || `用户${user.userId}`,
							employeeId: user.employeeId || user.userId,
							level: user.level || '无'
						}));
						console.log('转换后的业务员列表:', room.salespersonList);
					} else {
						console.log('后端未提供业务员信息，使用前端查询');
						// 如果没有业务员信息，使用原来的方式
						if (room.groupName) {
							room.salespersonList = await this.getSalespersonList(room.groupName);
						} else {
							room.salespersonList = [];
						}
					}
					
					// 获取订房人详细信息（如果后端没有提供）
					if (room.bookerId && !room.bookerName) {
						const bookerInfo = await this.getUserInfo(room.bookerId);
						if (bookerInfo) {
							room.bookerName = bookerInfo.name;
						}
					}
					
					// 获取服务员详细信息（如果后端没有提供）
					if (room.serviceStaffId && !room.serviceStaffName) {
						const serviceInfo = await this.getUserInfo(room.serviceStaffId);
						if (serviceInfo) {
							room.serviceStaffName = serviceInfo.name;
						}
					}
					
					// 获取DJ详细信息（如果后端没有提供）
					if (room.djId && !room.djName) {
						const djInfo = await this.getUserInfo(room.djId);
						if (djInfo) {
							room.djName = djInfo.name;
						}
					}
				}
				console.log('房间列表处理完成');
			}
		}
	}
</script>

<style lang="scss" scoped>
.shangban-container {
	padding: 20rpx;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.refresh-tip {
	text-align: center;
	padding: 20rpx;
	margin-bottom: 20rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 15rpx;
	
	.tip-text {
		font-size: 24rpx;
		color: #999;
		background-color: rgba(255, 255, 255, 0.8);
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		border: 1rpx solid #eee;
	}
	
	.manual-refresh-btn {
		background-color: #409eff;
		color: #fff;
		font-size: 24rpx;
		padding: 10rpx 30rpx;
		border-radius: 20rpx;
		border: none;
		line-height: 1.5;
		
		&:disabled {
			background-color: #c0c4cc;
			color: #fff;
		}
		
		&:active:not(:disabled) {
			background-color: #3a8ee6;
		}
	}
}

.status-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	display: flex;
	align-items: center;
	justify-content: space-between;

	.status-title {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
	}

	.status-buttons {
		display: flex;
		gap: 20rpx;

		.status-btn {
			padding: 15rpx 40rpx;
			border-radius: 30rpx;
			font-size: 28rpx;
			background-color: #f5f7fa;
			color: #666;
			border: 2rpx solid #dcdfe6;
			transition: all 0.3s ease;

			&.active {
				background-color: #409eff;
				color: #fff;
				border-color: #409eff;
			}

			&.disabled {
				opacity: 0.5;
				cursor: not-allowed;
				pointer-events: none;
			}

			&.applying {
				background-color: #e6a23c;
				color: #fff;
				border-color: #e6a23c;

				&.active {
					background-color: #e6a23c;
					border-color: #e6a23c;
				}
			}

			&:active {
				opacity: 0.8;
			}
		}
	}
}

.search-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

	.search-item {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		&:last-child {
			margin-bottom: 0;
		}

		.search-label {
			width: 120rpx;
			font-size: 28rpx;
			color: #333;
		}

		.search-input {
			flex: 1;
			height: 70rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
			background-color: #f5f7fa;
		}

		.date-picker {
			flex: 1;
			height: 70rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			background-color: #f5f7fa;

			.picker-text {
				height: 70rpx;
				line-height: 70rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
				color: #333;
			}
		}
	}

	.search-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
		gap: 20rpx;

		.search-btn, .reset-btn {
			flex: 1;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 8rpx;
			font-size: 28rpx;
			border: none;
		}

		.search-btn {
			background-color: #409eff;
			color: #fff;

			&:active {
				background-color: #3a8ee6;
			}
		}

		.reset-btn {
			background-color: #f5f7fa;
			color: #606266;
			border: 1rpx solid #dcdfe6;

			&:active {
				background-color: #e6e8eb;
			}
		}
	}
}

.data-list {
	/* 列表容器样式 */
}

.data-item {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #eee;
		padding-bottom: 20rpx;
		margin-bottom: 20rpx;

		.date {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.booker {
			font-size: 28rpx;
			color: #666;
		}
	}

	.item-body {
		.info-row {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.label {
				font-size: 28rpx;
				color: #555;
				flex-basis: 150rpx; /* 调整标签宽度 */
				margin-right: 20rpx;
			}

			.value {
				font-size: 28rpx;
				color: #333;
				flex: 1;
				text-align: right; /* 值右对齐 */
			}
		}
	}
}

.loading, .no-data {
	text-align: center;
	padding: 30rpx;
	color: #999;
	font-size: 28rpx;
}

/* 业务员列表样式 */
.salesperson-list {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx;
	margin-top: 10rpx;
}

.salesperson-item {
	background-color: #f0f9ff;
	border: 1rpx solid #b3d8ff;
	border-radius: 8rpx;
	padding: 8rpx 12rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 8rpx;
	font-size: 24rpx;
}

.salesperson-info {
	display: flex;
	align-items: center;
	gap: 8rpx;
	flex: 1;
}

.salesperson-name {
	color: #333;
	font-weight: 500;
}

.salesperson-id {
	color: #666;
	font-size: 22rpx;
}

.salesperson-level {
	color: #999;
	font-size: 22rpx;
	background-color: #e6f3ff;
	padding: 2rpx 8rpx;
	border-radius: 4rpx;
}

.apply-list {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}

	.apply-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;

		&:last-child {
			border-bottom: none;
		}

		.apply-info {
			flex: 1;

			.info-row {
				display: flex;
				margin-bottom: 10rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.label {
					width: 120rpx;
					color: #666;
					font-size: 28rpx;
				}

				.value {
					color: #333;
					font-size: 28rpx;
				}
			}
		}

		.apply-action {
			margin-left: 20rpx;

			.approve-btn {
				background-color: #67c23a;
				color: #fff;
				font-size: 28rpx;
				padding: 10rpx 30rpx;
				border-radius: 30rpx;
				border: none;

				&:active {
					opacity: 0.8;
				}
			}

			.reject-btn {
				background-color: #f56c6c;
				color: #fff;
				font-size: 28rpx;
				padding: 10rpx 30rpx;
				border-radius: 30rpx;
				border: none;
				margin-left: 10rpx;

				&:active {
					opacity: 0.8;
				}
			}
		}
	}
}

.guanliceng-user-search {
	margin-bottom: 20rpx;
	background: #f8f8f8;
	padding: 20rpx 20rpx 10rpx 20rpx;
	border-radius: 12rpx;
}

.guanliceng-user-search .search-item {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.guanliceng-user-search .search-label {
	min-width: 120rpx;
	font-size: 28rpx;
	color: #333;
}

.guanliceng-user-search .search-input {
	flex: 1;
	min-width: 0;
	max-width: 100%;
	border: 1px solid #e5e5e5;
	border-radius: 8rpx;
	padding: 12rpx 20rpx;
	font-size: 28rpx;
	background: #fff;
	margin-left: 12rpx;
	width: 70vw;
	box-sizing: border-box;
	height: 96rpx;
	line-height: 96rpx;
}

.guanliceng-user-search .date-picker {
	flex: 1;
	min-width: 0;
	max-width: 100%;
	border: 1px solid #e5e5e5;
	border-radius: 8rpx;
	padding: 12rpx 20rpx;
	font-size: 28rpx;
	background: #fff;
	margin-left: 12rpx;
	width: 70vw;
	box-sizing: border-box;
	height: 96rpx;
	line-height: 96rpx;
}

.guanliceng-user-search .picker-text {
	height: 96rpx;
	line-height: 96rpx;
	color: #333;
}

.guanliceng-user-search .search-buttons {
	display: flex;
	justify-content: flex-end;
	margin-bottom: 10rpx;
}

.guanliceng-user-search .search-btn {
	background: #3478f6;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	padding: 12rpx 40rpx;
	font-size: 28rpx;
	margin-left: 10rpx;
}

.guanliceng-user-search .search-btn-disabled {
	background: #c0c4cc;
	color: #fff;
	cursor: not-allowed;
}

.guanliceng-user-search .date-picker {
	flex: 1;
	min-width: 0;
	max-width: 100%;
	border: 1px solid #e5e5e5;
	border-radius: 8rpx;
	padding: 12rpx 20rpx;
	font-size: 28rpx;
	background: #fff;
	margin-left: 12rpx;
	width: 70vw;
	box-sizing: border-box;
	height: 96rpx;
	line-height: 96rpx;
}

.guanliceng-user-search .picker-text {
	height: 96rpx;
	line-height: 96rpx;
	color: #333;
}

.user-search-list {
	background: #fff;
	border: 1px solid #eee;
	border-radius: 8rpx;
	margin-top: 10rpx;
	max-height: 300rpx;
	overflow-y: auto;
}

.user-item {
	padding: 16rpx;
	border-bottom: 1px solid #f0f0f0;
	cursor: pointer;
	font-size: 28rpx;
	color: #333;
}

.user-item:last-child {
	border-bottom: none;
}
</style>
